package com.cn.serverline.lineicp.produce.service.impl;


import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cn.serverline.lineicp.produce.entity.TeSuspendRecords;
import com.cn.serverline.lineicp.produce.entity.dto.TeSuspendRecordsDto;
import com.cn.serverline.lineicp.produce.mapper.TeSuspendRecordsMapper;
import com.cn.serverline.lineicp.produce.service.ITeSuspendRecordsService;
import com.cn.serverline.lineicp.workshopPlan.mapper.PlanLineAutomaticMapper;
import com.cn.serverline.lineicp.workshopPlan.mapper.PlanLineScheduleMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 挂起 服务实现类
 * </p>
 *
 * @author 王凯炫
 * @since 2024-08-15
 */
@Service
public class TeSuspendRecordsServiceImpl extends ServiceImpl<TeSuspendRecordsMapper, TeSuspendRecords> implements ITeSuspendRecordsService {

    @Resource
    private TeSuspendRecordsMapper teSuspendRecordsMapper;

    @Resource
    private PlanLineAutomaticMapper planLineAutomaticMapper;

    @Resource
    private PlanLineScheduleMapper planLineScheduleMapper;
    /**
     * 添加挂起
     * @param teSuspendRecords
     */
    @Override
    public void add(List<TeSuspendRecordsDto> teSuspendRecords,Long zeroAssembly) {
        // 批量插入
        List<TeSuspendRecords> recordsList = new ArrayList<>();
        List<Long> taskId = new ArrayList<>();
        // 循环遍历
        for (TeSuspendRecordsDto teSuspendRecord : teSuspendRecords) {
            TeSuspendRecords suspendRecords = new TeSuspendRecords();
            BeanUtils.copyProperties(teSuspendRecord,suspendRecords);
            suspendRecords.setSuspendTime(new DateTime());
            // 计算挂起时间
            Duration duration = Duration.ofMinutes(Integer.parseInt(teSuspendRecord.getFixedTime()));
            suspendRecords.setEndTime(new Date(suspendRecords.getSuspendTime().getTime()+duration.toMillis()));
            recordsList.add(suspendRecords);
            taskId.add(suspendRecords.getTaskId());
        }
        // 批量插入
        this.saveBatch(recordsList);

        // 使用三目运算符来选择要调用的方法
        Runnable updateTaskIdAction = zeroAssembly == 0
                ? () -> planLineAutomaticMapper.updateTaskId(taskId)
                : () -> planLineScheduleMapper.updateTaskId(taskId);

        // 执行选择的方法
        updateTaskIdAction.run();

    }
}
